import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import storage from "@/utils/storage";
const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    redirect: "/main",
  },
  {
    path: "/main",
    name: "main",
    component: () =>
      import(/* webpackChunkName: "about" */ "@/views/main/Main.vue"),
  },
  {
    path: "/login",
    name: "login",
    component: () =>
      import(/* webpackChunkName: "about" */ "@/views/login/Login.vue"),
  },
  {
    path: "/:pathMatch(.*)*",
    component: () => import("@/views/NotFound/NotFound.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

// 跳转之前进行的操作  返回的路径就是即将要跳转的
router.beforeEach((to) => {
  // 如果用户即将跳转的不是login页面
  // 则判断用户是否登录 也就是缓存中是否有token
  // 如果有没有token则直接跳转到登录
  if (to.path !== "/login") {
    const token = storage.getStorage("token");
    if (!token) {
      return "/login";
    }
  }
});

export default router;
